<?php
/**
 * Created by PhpStorm.
 * User: yuanjie
 * Date: 2017/3/27
 * Time: 下午1:47
 */
use EasyWeChat\Foundation\Application;
use EasyWeChat\Payment\Order;
class WechatPaymentController extends BaseController
{
    public function prepareOrder(){
        $wx = Config::get('wechat.CHEPIN');
        $options = $wx['OPTION'];

        $app = new Application($options);
        $payment = $app->payment;

        $attributes = [
            'trade_type'       => 'NATIVE', // JSAPI，NATIVE，APP...
            'body'             => '洗车',
            'detail'           => '洗车服务费',
            'out_trade_no'     => '20170327004',
            'total_fee'        => 5000, // 单位：分
            'product_id'       => 'xiche',
            'notify_url'       => 'http://pay.yangche1hao.com/wechat/pay/notify', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
//            'openid'           => '当前用户的 openid', // trade_type=JSAPI，此参数必传，用户在商户appid下的唯一标识，
            // ...
        ];

        $order = new Order($attributes);
        $result = $payment->prepare($order);
//        if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
//            $prepayId = $result->prepay_id;
//        }
        return json_encode($result);
    }

    public function payBack(){
        $wx = Config::get('wechat.CHEPIN');
        $options = $wx['OPTION'];

        $app = new Application($options);
        $payment = $app->payment;
        $response = $payment->handleNotify(function($notify, $successful){
            // 你的逻辑
            Log::info('service_card_wx_pay',array('function'=>'payBack','notify'=>$notify , 'successful' => $successful));
            if($successful){
                if($notify->result_code="SUCCESS"){
                    $str=explode('-',$notify->out_trade_no);
                    switch ($str[0]) {
                        case 'xc'://如果是洗车单                            
                            $tran_no = date('YmdHis',time()).Common::generateCode(8);
                            $wpr=WeixinPayRecord::where("order_type",'xc')->where("order_id",$str[1])->first();
                            $wpr->weixin_order_no=$notify->transaction_id;
                            $wpr->status=1;
                            $wpr->save();
                            $cwo=CarWashOrder::find($str[1]);
                            CarWashOrder::where("order_id",$str[1])->update(array("status"=>1417));  
                            CarWashOrderPayRecord::where("order_id",$str[1])->update(array("status"=>1,"tran_no"=>$tran_no,"pay_id"=>$wpr->id));  

                            //记录用户充值 不记录充值记录  只记录流水
                            Account::record($cwo->user_id,$cwo->shop_id,1,$tran_no,1,106,$wpr->amount,'洗车单结算充值,洗车单号:'.$str[1]);
                            //记录用户支出
                            Account::record($cwo->user_id,$cwo->shop_id,1,$tran_no,2,206,$wpr->amount,'洗车单结算支出,洗车单号:'.$str[1]);
                            //记录公司账户收入
                            Account::record_base('1',$tran_no,1,106,$wpr->amount,'洗车单结算收入,洗车单号:'.$str[1]);

                            //记录订单账务关系
                            CarWashOrderAccount::insert(array('order_id' => $str[1],'tran_no' => $tran_no,));

                            // Account::record_base('1',$tran_no,1,'0106',$wpr->amount,'洗车收入');
                            // //记录订单账务关系
                            // CarWashOrderAccount::insert(array('order_id' => $str[1],'tran_no' => $tran_no,));
                            break;
                        case 'service_card'://如果是套餐卡
                            //验一下支付状态 如果不是处于支付中  不予支付
                            $wr=WeixinRecord::where("id",$str[1])->first();
                            $op=ServiceCardOrderPayRecord::find($wr->buss_id);
                            if($op->status!=5){
                                return false;
                            }
                            $tran_no = date('YmdHis',time()).Common::generateCode(8);
                            $wr->wx_transaction_id=$notify->transaction_id;
                            $wr->fee_type=$notify->fee_type;
                            $wr->cash_fee=$notify->cash_fee;
                            $wr->total_fee=$notify->total_fee;
                            $wr->is_subscribe=$notify->is_subscribe;
                            $wr->trade_type=$notify->trade_type;
                            $wr->time_end=$notify->time_end;
                            $wr->bank_type=$notify->bank_type;
                            $wr->out_trade_no=$notify->out_trade_no;
                            $wr->status=1;
                            $wr->save();
                            $sco=ServiceCardOrder::find($op->order_id);
                            ServiceCardOrder::where("order_id",$op->order_id)->update(array("status"=>1417,"pay_amount"=>$notify->total_fee));
                            ServiceCardOrderPayRecord::where("order_id",$op->order_id)->update(array("status"=>1,"tran_no"=>$tran_no,"pay_id"=>$wr->id));

                            //记录用户充值 不记录充值记录  只记录流水
                            Account::record($sco->user_id,$sco->shop_id,1,$tran_no,1,123,$wr->amount,'套餐卡订单结算充值,订单号:'.$op->order_id);
                            //记录用户支出
                            Account::record($sco->user_id,$sco->shop_id,1,$tran_no,2,223,$wr->amount,'套餐卡订单结算支出,订单号:'.$op->order_id);
                            //记录公司账户收入
                            Account::record_base('1',$tran_no,1,123,$wr->amount,'套餐卡订单结算收入,订单号:'.$op->order_id);

                            //记录订单账务关系
                            ServiceCardOrderAccount::insert(array('order_id' => $op->order_id,'tran_no' => $tran_no,));
                            // app 微站下单 生成相关套餐卡信息
                            if(in_array($sco->order_source,array(2,10))){
                                ServiceCardDetailPack::createServiceCardDetail($op->order_id);
                            }
                            break;
                        default:
                            break;
                    }
                    return true;
                }else{  
                    return false;
                }
            }else{
                return false;
            }
        });
        return $response;
    }

    /**
 * @Author:    dx
 * @DateTime:  2017-08-14 15:19:04
 * @Description: 微信支付 废弃
 */
    public function wx_js(){

        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
                'amount' => 'required',
                'trade_type' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $wx_user=$this->verificationUserToken(Input::get("token"),$response);
            if(is_null($wx_user)){
                break;
            }
            $order_id=Input::get("order_id");
            $amount=Input::get('amount');
            $trade_type = Input::get('trade_type');

            $order=ServiceCardOrder::find($order_id);
            if(is_null($order)){
                $response = Lang::get("error.service_card_order_error_95009");
                break;
            }
            $wx = Config::get('wechat.CHEPIN');
            $options = $wx['OPTION'];
            $app = new Application($options);
            $payment = $app->payment;
            $attributes = [
                'trade_type'       => $trade_type, // JSAPI，NATIVE，APP...
                'body'             => '套餐卡订单支付'.$order_id,
                'detail'           => '套餐卡订单支付',
                'out_trade_no'     => 'service_card-'.$order_id,
                'total_fee'        => 1,//$amount, // 单位：分  测试1分
                'product_id'       => 'service_card_pay',
                'notify_url'       => Config::get('wechat.pay_note_url'), // 支付结果通知网址，如果不设置则会使用配置里的默认地址
                'openid'           => $wx_user->openid, // trade_type=JSAPI，此参数必传，用户在商户appid下的唯一标识，
                // ...
            ];
            $weixin_order = new Order($attributes);
            $result = $payment->prepare($weixin_order);
            Log::info('service_card_wx_pay',array('function' => 'wx_js','response'=> $result));
            if ($result->return_code == 'SUCCESS'&&$result->result_code == 'SUCCESS'){
                $prepayId = $result->prepay_id;
                $config = $payment->configForJSSDKPayment($prepayId); // 这个方法是取得js里支付所必须的参数用的
                $wp=WeixinRecord::where("order_id",$order_id)->first();
                if(is_null($wp)){
                    $response = Lang::get("error.service_card_js_args_error_95011");
                    break;
                }
                $wp->order_id=$order_id;
                $wp->wx_pay_id=$result->prepay_id;
                $wp->status=0;
                $wp->amount=$amount;
                $wp->save();
                $response = array('code' => 0, 'msg' => 'ok', 'result' => array('config'=>$config));
            }else{
                $response = Lang::get("error.service_card_js_args_error_95011");
            }
        }while(false);
        Log::info("info", array("system" => "wechat2.0" ,"event" => "wx_js", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:    dx
     * @DateTime:  2017-08-14 15:19:04
     * @Description: 微信支付查询结果
     */
    public function order_query(){

        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $wx_user=$this->verificationUserToken(Input::get("token"),$response);
            if(is_null($wx_user)){
                break;
            }
            $order_id=Input::get("order_id");

            $scopr=ServiceCardOrderPayRecord::whereIn('status',array(0,5))->where('user_id',$wx_user->id)->where('pay_type',3)->where('order_id',$order_id)->first();
            if(is_null($scopr)){
                break;
            }
            $wx_record = WeixinRecord::where('buss_id',$scopr->id)->first();
            if(is_null($wx_record)){
                $response = Lang::get("error.service_card_wx_pay_record_error_95012");
                break;
            }
            if($wx_record->status == 1){
                $response = Lang::get("error.service_card_order_pay_record_status_error_95014");
                break;
            }
            $wx = Config::get('wechat.CHEPIN');
            $options = $wx['OPTION'];
            $app = new Application($options);
            $payment = $app->payment;

            $orderNo = $wx_record->out_trade_no;
            $result = $payment->query($orderNo);
            Log::info('service_card_wx_pay',array('function' => 'order_query','response'=> $result));
            if ($result->return_code == 'SUCCESS'&&$result->result_code == 'SUCCESS'){
                if($result->trade_state == 'CLOSED'){//关闭
                    $wx_record->status=2;
                    $scopr->status = 2;
                }
                if($result->trade_state == 'REVOKED'){//撤销
                    $wx_record->status=2;
                    $scopr->status = 6;
                }
                if($result->trade_state == 'USERPAYING'){//支付中
                    $wx_record->status=2;
                    $scopr->status = 5;
                }
                if($result->trade_state == 'PAYERROR'){//支付失败
                    $wx_record->status=2;
                    $scopr->status = 2;
                }
                if($result->trade_state == 'SUCCESS'){//支付成功
                    $wx_record->status=1;
                    $scopr->status = 1;
                }
                if($result->trade_state == 'NOTPAY'){//未支付  暂时不知道未支付是什么情况出现的
                    $wx_record->status=2;
                    $scopr->status = 4;
                }
            }else{
                $wx_record->status=2;
                $scopr->status = 2;
            }
            $scopr->save();
            $wx_record->save();
        }while(false);
        Log::info("info", array("system" => "wechat2.0" ,"event" => "order_query", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

}